package com.tom.architect.party3.day26.okhttp;

import android.util.Log;

import com.tom.architect.party3.day26.okhttp.interceptor.BridgeInterceptor;
import com.tom.architect.party3.day26.okhttp.interceptor.CacheInterceptor;
import com.tom.architect.party3.day26.okhttp.interceptor.CallServerInterceptor;
import com.tom.architect.party3.day26.okhttp.interceptor.Interceptor;
import com.tom.architect.party3.day26.okhttp.interceptor.RealInterceptorChain;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.net.ssl.HttpsURLConnection;

/**
 *
 */
public class RealCall implements Call {
    private final Request originalRequest;
    private final OkHttpClient client;

    public RealCall(Request request, OkHttpClient client) {
        this.originalRequest = request;
        this.client = client;
    }

    public static Call newCall(Request request, OkHttpClient okHttpClient) {
        return new RealCall(request, okHttpClient);
    }

    @Override
    public void enqueue(Callback callback) {
        // 异步请求
        AsyncCall asyncCall = new AsyncCall(callback);
        // 交给线程池。
        client.dispatcher.enqueue(asyncCall);
    }

    @Override
    public Response execute() {
        return null;
    }

    // 内部类。
    final class AsyncCall extends NamedRunnable {
        private Callback callback;

        public AsyncCall(Callback callback) {
            this.callback = callback;
        }

        @Override
        protected void execute() {
            // 真正开始访问网络，将request--> response。
            Log.e("TAG", "execute: 232323");
            // Volley，xUtils，Afinal，AsyHttpClient
            // 基于HttpUrlConnection; okHttp = Socket+ okio(IO输入输出流)

            final Request request = originalRequest;
            try {
                List<Interceptor> interceptors = new ArrayList<>();
                interceptors.add(new BridgeInterceptor());
                interceptors.add(new CacheInterceptor());
                interceptors.add(new CallServerInterceptor());

                // RealInterceptorChain 责任链分发给下一级。
                Interceptor.Chain chain = new RealInterceptorChain(interceptors,0,originalRequest);
                // 责任链最终处理的结果，返回到这里。
                Response response = chain.proceed(request); // 发给下一个处理
                callback.onResponse(RealCall.this, response);
            } catch (IOException e) {
                callback.onFailure(RealCall.this,e);
            }
        }
    }

}
